package com.luffy.devops


def init(String repo,String tag,String credentialsId,String context=".",dockerfile="Dockerfile"){
    echo "docker init初始化"
    this.repo = repo
    this.tag = tag
    if(env.TAG_NAME){                       //判断环境变量有 env.TAG_NAME ，则代表分支tag变化引起的构建
        this.tag = env.TAG_NAME
    }
    this.credentialsId = credentialsId      //Jenkins中设置凭据(保存账户密码)的ID
    this.context = context
    this.dockerfile = dockerfile
    this.fullAddress = "${this.repo}:${this.tag}"   // 192.168.136.10/demo/myblog:v1
    this.isLogin = false                    //判断docker login是否登录
    this.msg = new BuildMessage()           //实例化构建发送消息的对象
    return this
}

def login(){
    if (this.isLogin || this.credentialsId ==""){
        return this
    }
    withCredentials([usernamePassword(
            credentialsId: this.credentialsId,
            usernameVariable: 'USERNAME',
            passwordVariable: 'PASSWORD'
    )]) {
        String registry = this.getRegistry()
        retry(3) {
            try {
                sh "echo '登录docker' ; docker login ${registry} -u $USERNAME -p $PASSWORD"
                this.isLogin = true
            } catch (Exception exc) {
                echo "docker 登录错误 err:" + exc.toString()
            }
        }
    }
    return this
}

def getRegistry(){
    def sp = this.repo.split("/")
    if(sp.size() >0){
        return sp[0]
    }
    return this.repo
}


def build(){
    this.login()     //执行build先登录
    def isSuccess = false
    def errMessage = ""
    retry(3){
        try {
            sh "echo 'docker 构建中...' ; docker build ${this.context} -t ${this.fullAddress} -f ${this.dockerfile}"  // 执行shell的docker构建镜像命令，在双引号""中通过 ${xx}引用变量，groovy固定用法
            isSuccess = true
        }catch(Exception e){
            errMessage = e.toString()
        }
        def stage = env.STAGE_NAME + '-build'
        if(isSuccess){
            updateGitlabCommitStatus(name: "${stage}", state: 'success')
            //引用BuildMessage文件中的类和方法
            echo "build成功通知gitlab"
            this.msg.updateBuildMessage(env.BUILD_TASKS, "${stage} OK...  √")
            echo "build成功消息以添加钉钉"
        }else{
            updateGitlabCommitStatus(name: "${stage}", state: 'failed')
            echo "build失败通知gitlab"
            this.msg.updateBuildMessage(env.BUILD_TASKS, "${stage} Failed...  x")
            echo "build失败消息以添加钉钉"
            //抛出异常
            error errMessage
        }
    }
    return this
}

def push(){
    this.login()
    def isSuccess = false
    def errMessage = ""
    retry(3) {
        try {
            sh "echo 'docker push中...' ; docker push ${this.fullAddress} "
            env.CURRENT_IMAGE = this.fullAddress
            isSuccess = true
        }catch(Exception e) {
            errMessage = e.toString()
        }
        def stage = env.STAGE_NAME + '-push'
        if(isSuccess){
            updateGitlabCommitStatus(name: "${stage}", state: 'success')
            echo "push成功通知gitlab"
            this.msg.updateBuildMessage(env.BUILD_TASKS, "${stage} OK...  √")
            echo "push成功消息以添加钉钉"
        }else{
            updateGitlabCommitStatus(name: "${stage}", state: 'failed')
            echo "push失败通知gitlab"
            this.msg.updateBuildMessage(env.BUILD_TASKS, "${stage} Failed...  x")
            echo "push失败消息以添加钉钉"
            //抛出异常
            error errMessage
        }
    }
    return this
}

